<!-- 电子签章模块 -->
<template>
  <el-container class="electronicSignature">
    <!-- <el-header height="36px">
      <header-title :title="$route.meta.title" />
    </el-header> -->
    <el-main class="mainDetails">
      <div>
        <!-- <div class="topRemark">
          <span class="asterisk">*</span>
          签署状态为转化失败时，请上传人重新上传PDF文件。
        </div> -->
        <SearchPanel title="查询条件" show-fold @setHeight="setHeight">
          <div ref="queryFormBox" class="search-flex-box">
            <MyForm
              ref="formRef"
              v-model="queryParams"
              :form-option="formOption"
              :select-list="dicLists"
              @handleEvent="handleEvent"
            >
              <template #orgIds>
                <div @click="activeUnit">
                  <el-input v-model="customCheck" class="construct" :readonly="true" placeholder="请选择">
                    <i slot="suffix" class="el-icon-more" />
                  </el-input>
                </div>
              </template>
            </MyForm>
            <div class="searchBtn">
              <el-button type="primary" class="pms-button-primary" @click="doSearch">查询</el-button>
              <el-button class="pms-button-primary" size="small" @click="dialogCheckbox = true">
                自定义列
              </el-button>
            </div>
          </div>
        </SearchPanel>
        <SearchList title="查询结果" style="margin-top: 16px">
          <template #header-btn>
            <BtnConfig ref="btnConfigRef" :btn-configs="btnOption" @propClick="btnClick" />
          </template>
          <template #body>
            <MyTable
              id="id"
              ref="myTableRef"
              :table-data="tableData"
              :columns="colOption"
              :col-option-enum="dicLists"
            >
              <template #docName="{ scope }">
                <el-button type="text" @click="goPage(scope)">{{ scope.docName }}</el-button>
              </template>
              <template #state="{ scope }">
                <el-button type="text" @click="goState(scope)">
                  {{ signStateVal(scope.state) }}
                </el-button>
              </template>
            </MyTable>
            <pagination
              v-if="pageParam.total > 10"
              :total="pageParam.total"
              :page.sync="pageParam.pageNum"
              :limit.sync="pageParam.pageSize"
              @pagination="doSearch"
            />
          </template>
        </SearchList>
        <!-- 选择建设单位 -->
        <el-dialog
          v-dialogDrag
          title="选择建设单位"
          width="30%"
          :append-to-body="true"
          :modal-append-to-body="true"
          :modal="true"
          :close-on-click-modal="false"
          :lock-scroll="true"
          class="pms-dialog"
          :visible.sync="dialogUnit"
        >
          <div class="dialogForm">
            <ChooseUnit ref="chooseUnitRef" v-model="queryParams.orgIds" />
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" class="pms-button-primary" size="small" @click="verifyUnit">确 定</el-button>
            <el-button type="primary" class="pms-button-primary" @click="dialogUnit = false">取 消</el-button>
          </div>
        </el-dialog>
        <!-- 打开签署状态弹框列表-审批流程 -->
        <el-dialog
          v-if="dialogState"
          v-dialogDrag
          title="审批流程"
          width="50%"
          :append-to-body="true"
          :modal-append-to-body="true"
          :modal="true"
          :close-on-click-modal="false"
          :lock-scroll="true"
          class="pms-dialog"
          :visible.sync="dialogState"
        >
          <div class="dialogForm">
            <SignStatusList ref="signStatusRef" :sign-status-id="signStatusId" />
          </div>
        </el-dialog>
        <el-dialog
          v-dialogDrag
          title="列表字段配置"
          width="50%"
          :append-to-body="true"
          :modal-append-to-body="true"
          :modal="true"
          :close-on-click-modal="false"
          :lock-scroll="true"
          class="pms-dialog"
          :visible.sync="dialogCheckbox"
        >
          <div class="dialogCheckbox">
            <SetDynamics
              ref="customRef"
              :fixed-check-option="fixedCheckOption"
              :custom-check-option="customCheckOption"
            />
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button class="pms-button-primary" size="small" @click="activeCustomCheck">确 定</el-button>
            <el-button class="pms-button-primary" size="small" @click="dialogCheckbox = false">取 消</el-button>
          </div>
        </el-dialog>
      </div>
    </el-main>
  </el-container>
</template>

<script>
// import HeaderTitle from '@/components/basic/HeaderTitle'
import axios from 'axios'
import SearchPanel from '@/components/basic/SearchPanel'
import MyForm from '@/components/basic/myForm'
import SearchList from '@/components/basic/SearchList'
import MyTable from '@/components/basic/myTable'
import SysConst from '@/common/const'
import SetDynamics from '@/components/basic/setDynamics.vue'
import BtnConfig from '@/components/basic/btnConfig.vue'
import ChooseUnit from '../eleSignVerConfig/chooseUnit.vue'
import SignStatusList from '@/components/eleSignature/signStatusList.vue'
import { getDropdownData } from '@/api/common' // 字典接口
import { formOption, colOption, btnOption, customCheckOption } from '.'
import { disableScroll, enableScroll, msgInfoEl, downloadFileFun } from '@/utils' // singleDownload, mulDownload, downloadFileFun
import { queryOrgApi } from '@/api/attachManagement/electronicSign/eleSignVerConfig'
import {
    getListApi,
    verifyFileKeyApi,
    processCancelApi,
    asyncExportApi,
    delApi,
    checkPersonApi,
    getSignFlowDocUrlsApi // 预览签署中的pdf
} from '@/api/attachManagement/electronicSign/electronicSignature'
import {
    getPrjStageApi,
    getPrjNodeNameApi,
    batchDownloadApi, // 批量下载
    downloadApi // 单个文件下载
} from '@/api/attachmentInfo'
import { queryDocTypeApi } from '@/api/attachManagement/electronicSign/electronicSignConfig'

export default {
    name: 'ElectronicSignature',
    components: {
        // HeaderTitle,
        SearchPanel,
        SearchList,
        MyTable,
        MyForm,
        SetDynamics,
        BtnConfig,
        ChooseUnit,
        SignStatusList
    },
    data() {
        return {
            queryParams: {
                prjYear: new Date().getFullYear().toString()
            }, // 查询数据
            formOption, // 查询条件配置项
            customCheck: '', // 查询条件建设单位选择后显示
            dialogUnit: false, // 建设单位弹框
            tableData: [], // 列表数据
            colOption, // 列表表头
            btnOption, // 列表按钮
            fixedCheckOption: colOption, // 固定字段
            customCheckOption, // 自定义字段
            dialogCheckbox: false, // 自定义列表弹框
            dicLists: {}, // 下拉框字典选项集合
            dialogState: false, // 审批流程列表弹框
            signStatusId: '', // 审批流程Id
            // 分页信息
            pageParam: {
                pageSize: SysConst.PAGESIZE, // 每页显示val条
                pageNum: SysConst.CURRENT_PAGE, // 当前页
                total: SysConst.TOTAL // 总数
            }
        }
    },
    created() {
        this.$nextTick(() => {
            this.setHeight(false)
        })
        this.getDictData()
        this.getPrjStage()
        this.getPrjNodeName([])
        this.queryDocType()
        this.queryOrg()
        this.doSearch()
    },
    methods: {
        // 查看数据
        doSearch(item) {
            const params = {
                pageNum: item?.page || SysConst.CURRENT_PAGE,
                pageSize: item?.limit || SysConst.PAGESIZE,
                ...this.queryParams
            }
            getListApi(params).then(res => {
                if (+res.code !== 200) {
                  return Promise.reject(res)
        }
                this.tableData = res.data?.dataList
                this.pageParam.total = res.data?.totalCount || 0
                this.pageParam.pageSize = item?.limit || SysConst.PAGESIZE
                this.pageParam.pageNum = item?.page || SysConst.CURRENT_PAGE
            })
        },
        // 枚举签署状态
        signStateVal(state) {
            // 显示检验
            if (!state && state !== 0) return ''
            if (state === '-') return state
            let propName = '' // 定义返回字段
            const propObj = this.dicLists['SIGN_STATE2'].find(sign => sign.dictId === state) || {}
            propName = JSON.stringify(propObj) !== '{}' ? propObj.dictName : ''
            return propName
        },
        // 查询条件事件
        handleEvent(prop, val) {
            console.log(prop, val, 'hjhjbj')
            if (prop === 'prjStatusNew') {
                this.getPrjNodeName(val)
                this.queryParams.prjNodeId = []
            }
        },
        // 列表按钮点击事件
        btnClick(fun, row) {
            this[fun](row)
        },
        // 验签
        async visa(row) {
            if (row[0].state !== '3') {
                return this.$message.info('该文件仅支持签署状态为已签署完成时验签')
            }
            console.log(row.map(item => item.id.toString()), 'row.map(item => item.id) ')
            const res = await this.checkPerson({ ids: row.map(item => item.id.toString()).join() })
            if (res.isInner === 0) {
                return this.$message.error('当前所选文件仅支持本单位人员进行验签操作')
            }
            if (res.isOwn === 0) {
                return this.$message.error('当前所选文件仅支持本人上传的文件发起验签操作')
            }
            verifyFileKeyApi({ id: row[0].id.toString() }).then(res_ => {
                if (+res_.code !== 200) {
                  return Promise.reject(res_)
        }
                this.$message.success('验签结果正确')
                this.doSearch({
                    page: this.pageParam.pageNum,
                    limit: this.pageParam.pageSize
                })
            })
        },
        // 作废
        async void(row) {
            if (row[0].state !== '3') {
                return this.$message.info('该文件仅支持签署状态为已签署完成时作废')
            }
            const res = await this.checkPerson({ ids: row.map(item => item.id.toString()).join() })
            if (res.isOwn === 0) {
                return this.$message.error('当前所选文件仅支持本人上传的文件发起作废操作')
            }
            processCancelApi({ id: row[0].id.toString() }).then(res_ => {
                if (+res_.code !== 200) {
                  return Promise.reject(res_)
        }
                this.$message.success('作废成功！')
                this.doSearch({
                    page: this.pageParam.pageNum,
                    limit: this.pageParam.pageSize
                })
                this.$refs.myTableRef.clearSelection()
            })
        },
        // 下载
        async download(row) {
            const fileDownloadNo = row.find(item => item.fileId === '' || item.fileId === null || item.fileId === undefined) || {}
            if (JSON.stringify(fileDownloadNo) !== '{}') {
                return msgInfoEl({
                    type: 'info',
                    message: `所选${fileDownloadNo.docName}文件不支持下载`
                })
            }
            // const fileList = row.map(item => ({
            //     filePath: item.docUrl,
            //     fileName: item.docName
            // }))
            const flag = row.every(item => item.prgCode === row[0].prgCode)
            if (!flag) {
               return this.$message.info('仅支持按项目维度批量下载，需要搜索项目后支持批量下载')
            }
            const res = await this.checkPerson({ ids: row.map(item => item.id.toString()).join() })
            if (res.isOwn === 0) {
                return this.$message.error('当前所选文件仅支持本人上传的文件发起下载操作')
            }
            const fileName = row.length > 1 ? '电子签章文件.zip' : row[0].docName
            // 单个文件下载时的参数
            const params = {
                fileId: row[0].fileId,
                fileName: row[0].docName
            }
            // // 多个文件下载时的参数
            const batchParams = row.map(item => ({
                fileId: item.fileId,
                fileName: item.docName
            }))
            if (row.length > 1) {
                // mulDownload(fileList, fileName)
                // 批量下载
                batchDownloadApi({ fileMap: batchParams }).then(ress_ => {
                    console.log(ress_, '下载')
                    downloadFileFun(ress_, fileName)
                })
            } else {
                // singleDownload(fileList, fileName)
                // 单个文件下载
                downloadApi(params).then(res_res => {
                    console.log(res_res, '下载')
                    downloadFileFun(res_res, fileName)
                })
            }
        },
        // 导出
        async derive(row) {
            const params = {
                id: row.map(item => item.id),
                ...this.queryParams
            }
            const res = await this.checkPerson({ ids: row.map(item => item.id.toString()).join() })
            if (res.isOwn === 0) {
                return this.$message.error('当前所选文件仅支持本人上传的文件发起导出操作')
            }
            asyncExportApi(params).then(res_sing => {
                if (+res_sing.code !== 200) {
                  return Promise.reject(res_sing)
        }
                this.$message.success('导出成功')
            })
        },
        // 删除
        async delete(row) {
            if (row.length > 1) {
                return this.$message.info('当前仅支持单条数据操作')
            }
            const { fileBs, state } = row[0]
            if (fileBs !== '0') {
                return this.$message.info('该文件类型为系统生成或系统生成/手动编辑，此类文件不支持删除操作')
            }
            if (!['3', '4', '5', '9'].includes(state)) {
                return this.$message.info('当前所选数据的签署状态不支持删除操作')
            }
            const res = await this.checkPerson({ ids: row.map(item => item.id.toString()).join() })
            if (res.isOwn === 0) {
                return this.$message.error('当前所选文件仅支持本人上传的文件发起删除操作')
            }
            const contentBody = window.top.document.body
            this.$confirm(`确认删除所选数据, 是否继续?`, '删除', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                cancelButtonClass: 'pms-zr-button',
                confirmButtonClass: 'pms-zr-button-primary',
                type: 'warning'
            }).then(() => {
                this.deleteData({ id: row.map(item => item.id).join() }, contentBody)
            }).catch(() => {
                enableScroll(contentBody)
                console.log('取消删除了')
            })
            // el-message-box__wrapper
            // 将弹框挂载在最外层
            this.$nextTick(() => {
                const msgBox = document.querySelector('.el-message-box__wrapper')
                contentBody.appendChild(msgBox)
                disableScroll(contentBody)
            })
        },
        // 调用删除接口
        deleteData(params, contentBody) {
            delApi(params).then(res => {
                if (+res.code !== 200) {
                  return Promise.reject(res)
        }
                this.doSearch({
                    page: this.pageParam.pageNum,
                    limit: this.pageParam.pageSize
                })
                this.$refs.myTableRef.clearSelection()
                this.$message.success('删除成功!')
                enableScroll(contentBody)
            })
        },
        // 点击去往E签宝
        goPage(row) {
            getSignFlowDocUrlsApi({ id: row.id }).then(res => {
                if (+res.code !== 200) {
                  return Promise.reject(res)
        }
                if (res.data) {
                    axios.get(res.data, {
                        responseType: 'blob',
                        cache: true,
                        headers: {
                            'Content-Disposition': 'inline'
                        }
                    }).then(r => {
                            const blob = new Blob([r.data], { type: 'application/pdf;charset-UTF-8' })
                            // const blob = new Blob([r.data], { type: r.headers['content-type'] })
                            const url = window.URL.createObjectURL(blob)
                            window.open(url, '_blank')
                            URL.revokeObjectURL(url) // 释放内存
                    })
                }
            })
        },
        // 点击签署状态
        goState(row) {
            console.log(row, '点击签署状态')
            this.dialogState = true
            this.signStatusId = row.id.toString()
        },
        // 重置
        // resetSearch() {
        //     this.$refs.formRef.reset()
        //     this.doSearch()
        // },
        // 选择建设单位
        activeUnit() {
            this.dialogUnit = true
        },
        // 确定单位
        verifyUnit() {
            const { checkedKeys, checkedNodes } = this.$refs.chooseUnitRef
            this.$set(this.queryParams, 'orgIds', checkedKeys)
            const list = checkedNodes.map((item) => item.orgName)
            this.customCheck = list.join().replaceAll(',', '、')
            this.dialogUnit = false
        },
        // 自定义列字段弹框-点击确认
        activeCustomCheck() {
            const list = this.$refs.customRef.checkboxValue
            this.colOption = [...colOption, ...list]
            this.dialogCheckbox = false
        },
        // 校验是否本人数据/是否内部人员接口
        async checkPerson(params) {
            const res = await checkPersonApi(params)
            if (res.success) {
                return res.data
            } else {
                this.$message.error(res.message)
            }
        },
        // 获取下拉框数据
        async getDictData() {
            const arr = ['IS_NEWBUSINESS', 'PROJ_TYPE', 'SIGN_STATE2', 'BUILD_MODES']
            const promises = arr.map(item => getDropdownData(item))
            const results = await Promise.all(promises)
            arr.forEach((item, i) => {
                this.$set(this.dicLists, item, results[i].data ?? [])
            })
            this.$set(this.dicLists, 'FILE_UPLOAD_MODES', SysConst.UPLOAD_MODES)
        },
        // 获取文档类型
        async queryDocType(val) {
            const res = await queryDocTypeApi({ nodeId: val ?? '' })
            this.$set(this.dicLists, 'DOC_TYPE', res.data ?? [])
        },
        // 查询建设单位
        async queryOrg() {
            const res = await queryOrgApi()
            this.$set(this.dicLists, 'BUILD_UNIT', res.data)
        },
        // 获取项目阶段字典
        async getPrjStage() {
            const res = await getPrjStageApi()
            this.$set(this.dicLists, 'PRO_STAGE', res.data)
        },
        // 获取项目节点字典
        async getPrjNodeName(val) {
            const res = await getPrjNodeNameApi({ stageList: val.join() ?? '' })
            this.$set(this.dicLists, 'PRO_NODE', res.data)
        },
        // 设置高度
        setHeight(isFold) {
            const child = this.$refs.formRef.$refs
            const height = (formOption.itemData.length / 3).toFixed() - 0
            // const height = (child.queryFormRef.$children.length / 3).toFixed() - 0
            this.$refs.queryFormBox.style.height = isFold ? `${height * 24}px` : '54px'
            child.myFormRef.style.height = isFold ? `${height * 24}px` : '54px'
        },
        // 盖章
        async stamp(row) {
            if (row.length > 1) {
                return this.$message.info('当前仅支持单条数据操作')
            }
            if (!(row[0].state === '2' || row[0].state === '8')){
                return this.$message.info('该文件仅支持签署状态为签署中/作废中盖章')
            }
            const res = await this.checkPerson({ ids: row.map(item => item.id.toString()).join() })
            if (res.isOwn === 0) {
                return this.$message.error('当前所选文件仅支持本人上传的文件发起盖章操作')
            }
            if (row[0].signUrl) {
                window.open(row[0].signUrl)
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.search-flex-box {
    // display: flex;
    // justify-content: space-between;
    height: auto;
}
.searchBtn {
    width: 100px;
    margin-left: auto;
    display: flex;
    margin-top: 4px;
    flex-direction: column;
    .el-button + .el-button {
        margin-left: 0;
        margin-top: 8px;
    }
}

.electronicSignature {
    width: 100%;
    .mainDetails {
        padding: 0 25px;
    }
    .topRemark {
        // background-color: #fdf5e6;
        background-color: #ffefd5;
        width: 100%;
        height: 40px;
        line-height: 40px;
        padding-left: 10px;
        font-size: 14px;

        .asterisk {
            color: #f00;
            margin-right: 2px;
            font-size: 18px;
        }
    }

    .customBtn {
        height: 20px;
        line-height: 20px;
        font-size: 14px;
        margin: 10px 20px 10px 90%;
        cursor: pointer;

        .el-icon-s-tools {
            font-size: 20px;
            color: #999;
            margin-right: 6px;
        }
    }
}

.el-button--text {
    color: #02A7F0;
}

.el-button--primary {
    color: #fff;
}
.dialog-footer {
    display: flex;
    justify-content: center;
}
::v-deep .el-button + .el-button {
    color: #fff;
}
// 弹框样式
::v-deep .el-dialog__body {
    max-height: 400px;
    overflow-y: auto;
}
// 滚动条样式
::v-deep .el-dialog__body::-webkit-scrollbar {
  // 滚动条整体样式
  width: 6px; //高宽分别对应横竖滚动条的尺寸
  height: 10px;
}
::v-deep .el-dialog__body::-webkit-scrollbar-thumb {
  // 滚动条里面小方块
  border-radius: 10px;
  // -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: #f2f3f5;
}
</style>
